package com.ics.cmsadmin.frame.profit.factory;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ics.cmsadmin.frame.core.exception.ExceptionUtils;
import com.ics.cmsadmin.frame.profit.ExpressionConstant;
import com.ics.cmsadmin.frame.profit.bean.GradientRateData;
import com.ics.cmsadmin.frame.profit.role.GradientRateRole;
import com.ics.cmsadmin.frame.profit.role.ProfitRole;
import lombok.extern.log4j.Log4j2;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

import static com.ics.cmsadmin.frame.profit.ProfitTypeEnum.GRADIENT_RATE;

/**
 * Created by Administrator on 2017/4/19.
 */
@Log4j2
public class GradientRateRoleFactory extends ProfitRoleFactory{

    @Override
    public void verifyExpression(String expression) {
        super.commonVerifExpression(GRADIENT_RATE, expression);
    }

    @Override
    protected ProfitRole newProfitRole(String expression) {
        List<BigDecimal> rates = new ArrayList<>();
        List<BigDecimal> limits = new ArrayList<>();
        Matcher numberMatcher = ExpressionConstant.NUMBER_PATTERN.matcher(expression);
        for (int i = 0;numberMatcher.find();i ++){
            if (i % 2 == 0){
                rates.add(new BigDecimal(numberMatcher.group()));
            }else{
                limits.add(new BigDecimal(numberMatcher.group()));
            }
        }
        return new GradientRateRole(rates, limits);
    }

    @Override
    public String generateExpression(Object data) {
        if (data == null){
            return null;
        }
        try {
            Gson gson = new Gson();
            List<GradientRateData> ruleDataList = gson.fromJson(gson.toJson(data), new TypeToken<List<GradientRateData>>() {
            }.getType());
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ruleDataList.size(); i ++){
                GradientRateData item = ruleDataList.get(i);
                if (i == 0){
                    sb.append(String.format("%s%%", item.getRate()));
                }else {
                    sb.append(String.format("<%s<%s%%", item.getMinStudent(), item.getRate(), item.getMaxStudent()));
                }
            }
            return sb.toString();
        }catch (Exception e){
            log.warn("生成表达式异常" + ExceptionUtils.collectExceptionStackMsg(e));
            return null;
        }
    }
}
